package net.deuce.perf;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;

public class JMeterSummaryStats {

    private File summaryFile;
    private List<Double> thresholds = new LinkedList<Double>();
    private Log log = LogFactory.getLog(getClass());

    public JMeterSummaryStats(File f, List<Double> thresholds) {
        //log.trace("");
        this.summaryFile = f;
        if (thresholds != null) {
            this.thresholds.addAll(thresholds);
        }
    }

    public ClientStats calculateStats() throws DocumentException {
        //log.trace("");
        SAXReader reader = new SAXReader();
        ClientStats stats = new ClientStats(thresholds);
        Document document = reader.read(summaryFile);
        Element root = document.getRootElement();
        for ( Iterator i = root.elementIterator( "httpSample" ); i.hasNext(); ) {
            Element el = (Element) i.next();
            long time = new Long(el.attributeValue("t"));
            if ("Non HTTP response code: java.net.SocketTimeoutException".equals(el.attributeValue("rc"))) {
                stats.addError();
                continue;
            }
            int rc = 500;
            String rcValue = el.attributeValue("rc");
            if ("Non HTTP response code: java.net.SocketTimeoutException".equals(rcValue)) {
                rc = 200;
            } else if (rcValue.matches("^[0-9]+$")) {
                rc = new Integer(rcValue);
            }
            String label = el.attributeValue("lb");
            String rm = el.attributeValue("rm");
            if (rc == 200) {
                stats.addSuccessTime(label, time);
            } else if (rc >= 400) {
                stats.addError();
            }
        }
        return stats;
    }
}
